import subprocess
import sys
from pathlib import Path


def format_files_recursive(directory):
    extensions = {".c", ".h", ".cpp", ".hpp", ".cc", ".cxx"}
    directory = Path(directory)
    
    if not directory.exists():
        print(f"Error: Directory '{directory}' does not exist")
        return
    
    files_found = []
    for file_path in directory.rglob("*"):
        if file_path.suffix in extensions:
            files_found.append(file_path)
    
    if not files_found:
        print(f"No C/C++ files found in '{directory}'")
        return
    
    print(f"Found {len(files_found)} files to format in '{directory}'")
    
    for i, file_path in enumerate(files_found, 1):
        print(f"[{i}/{len(files_found)}] Formatting: {file_path}")
        try:
            subprocess.run(["clang-format", "-i", str(file_path)], check=True)
        except subprocess.CalledProcessError as e:
            print(f"Error: {e}")
        except FileNotFoundError:
            print("Error: clang-format not found. Please install clang-format first.")
            return


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python fromat.py <directory>")
        print("Example: python fromat.py Main/")
        sys.exit(1)
    
    target_directory = sys.argv[1]
    format_files_recursive(target_directory)
